<template>
  <div class="health-code" v-if="healthCode">
    <header>
      <img src="../assets/imgs/banner.png" alt="" />
    </header>
    <div class="card code">
      <div class="code-head">
        <span>{{ healthCode.name | nameFilter }}的健康码</span>
        <span>{{ time }}</span>
      </div>
      <div class="code-body">
        <img class="banner1" src="../assets/imgs/banner1.png" alt="" />
        <div class="body_title">
          <img
            class="left"
            v-if="healthCode.codeStr == '绿码'"
            src="../assets/imgs/right_green.png"
            alt=""
          />
          <img
            class="left"
            v-if="healthCode.codeStr == '黄码'"
            src="../assets/imgs/left_yellow.png"
            alt=""
          />
          <img
            class="left"
            v-if="healthCode.codeStr == '红码'"
            src="../assets/imgs/left_red.png"
            alt=""
          />
          <span
            :style="
              healthCode.codeStr == '绿码'
                ? 'color: #0b6e3e;'
                : healthCode.codeStr == '黄码'
                ? 'color: #d67b1a;'
                : healthCode.codeStr == '红码'
                ? 'color: #e42926'
                : 'color: #000'
            "
            >{{ healthCode.codeStr }}</span
          >
          <img
            class="right"
            v-if="healthCode.codeStr == '绿码'"
            src="../assets/imgs/left_green.png"
            alt=""
          />
          <img
            class="right"
            v-if="healthCode.codeStr == '黄码'"
            src="../assets/imgs/right_yellow.png"
            alt=""
          />
          <img
            class="right"
            v-if="healthCode.codeStr == '红码'"
            src="../assets/imgs/right_red.png"
            alt=""
          />
        </div>
        <div class="vue-qr">
          <vue-qr
            :text="healthCode.encodeData"
            :size="300"
            :margin="10"
            :colorDark="
              healthCode.codeStr == '绿码'
                ? '#5bb06f'
                : healthCode.codeStr == '黄码'
                ? '#e48826'
                : healthCode.codeStr == '红码'
                ? '#e42926'
                : '#000'
            "
          />
        </div>
      </div>
      <div
        class="code-foot"
        :style="
          healthCode.codeStr == '绿码'
            ? 'color: #0b6e3e;'
            : healthCode.codeStr == '黄码'
            ? 'color: #d67b1a;'
            : healthCode.codeStr == '红码'
            ? 'color: #e42926'
            : 'color: #000'
        "
      >
        健康宁波,你我共建
      </div>
    </div>
    <div class="whiteBox">
      <div class="card trip-code" @click="toLogin">
        <img
          class="cardTop"
          v-if="healthCode.value == '1'"
          src="../assets/imgs/cardTop_green.png"
          alt=""
        />
        <img
          class="cardTop"
          v-if="healthCode.value == '2'"
          src="../assets/imgs/cardTop_orange.png"
          alt=""
        />
        <img
          class="cardTop"
          v-if="healthCode.value == '3'"
          src="../assets/imgs/cardTop_qing.png"
          alt=""
        />
        <div class="trip-pic">
          <img
            v-if="healthCode.value == '1'"
            src="../assets/imgs/green.png"
          /><img
            v-if="healthCode.value == '2'"
            src="../assets/imgs/orange.png"
          />
          <img
            v-if="healthCode.value == '3'"
            src="../assets/imgs/qing.png"
          />
        </div>
        <div class="text-center1">
          近14天涉足地区:
          <span
          v-if="healthCode.value != '3'"
            :style="
              healthCode.value == '1' ? 'color:#2aa469' : 'color: #FF7E11;'
            "
            >{{ healthCode.value | valueFulter }}
            <img class="img-right" src="../assets/imgs/right.png" alt="" /></span
          >
          <span
            v-else
            :style="
              healthCode.value == '3' ? 'color:#15498F' : ''
            "
            >无行程
            <img class="img-right" src="../assets/imgs/right.png" alt="" /></span
          >
        </div>
      </div>

      <div class="measure">
        <div class="card" v-if="nucleicAcidInfos.length > 0" @click="nuc" 
          :style="{borderColor:hours(nucleicAcidInfos[0].receivetime)=='72小时'?'green':(hours(nucleicAcidInfos[0].receivetime)=='48小时'?'green':'#e5e5e5')}"
          >
          <div v-if="hours">
              <!-- <div class="timeBox" v-if="hours(nucleicAcidInfos[0].receivetime)=='72小时'" :style="hours(nucleicAcidInfos[0].receivetime)=='72小时'?'background: linear-gradient(to right,#2dd13d, #7fd12e, #2dd13d);':null">{{hours(nucleicAcidInfos[0].receivetime)}}</div> -->
              <div class="timeBox" v-if="hours(nucleicAcidInfos[0].receivetime)=='48小时'" :style="hours(nucleicAcidInfos[0].receivetime)=='48小时'?'background: linear-gradient(to right,#ff6f02, #ffba00, #ff6f00);color:#fff':null">{{hours(nucleicAcidInfos[0].receivetime)}}</div>
              <div class="timeBox" v-if="hours(nucleicAcidInfos[0].receivetime)==''" style="background: none;">{{hours(nucleicAcidInfos[0].receivetime)}}</div>
          </div>
          <div class="flex">
            <img src="../assets/imgs/icon11.png" alt="" />
            <div class="title">核酸检测</div>
            <img src="../assets/imgs/right.png" alt="" />
          </div>
          <div class="nuclein-result">{{ nucleicAcidInfos[0].result }}</div>
          <div class="text-center">
            
            <!-- {{ nucleicAcidInfos[0].receivetime | timeFiter }} -->
            {{ nucleicAcidInfos[0].receivetime  }}
          </div>
          <div class="text-center">{{ nucleicAcidInfos[0].jgmc }}</div>
        </div>
        <div class="card" v-if="nucleicAcidInfos.length == 0">
          <div class="flex nores">
            <img src="../assets/imgs/icon11.png" alt="" />
            <div>核酸检测</div>
          </div>
          <div class="text-error">暂无核酸记录</div>
        </div>
        <div class="card"  @click="vac" v-if="vaccinationInfos.length > 0"
          :style="{borderColor:vaccinationInfos[0].vaccinationTime==3?'green':'#e5e5e5'}"
          >
            <div class="zhenBox none" v-if="vaccinationInfos[0].vaccinationTime==0">暂无疫苗记录</div>
            <div class="zhenBox one" v-if="vaccinationInfos[0].vaccinationTime==1">请尽快完成第二针</div>
            <div class="zhenBox two" v-if="vaccinationInfos[0].vaccinationTime==2">请尽快完成第三针</div>
            <div class="zhenBox three" v-if="vaccinationInfos[0].vaccinationTime==3">安心</div>
          <div class="flex">
            <img src="../assets/imgs/icon12.png" alt="" />
            <div>新冠疫苗</div>
            <img src="../assets/imgs/right.png" alt="" />
          </div>
          <div class="vaccines-result">
            已接种{{ vaccinationInfos[0].vaccinationTime }}针
          </div>
          <div class="text-center">
            <!-- {{ vaccinationInfos[0].vaccinationDateTime | timeFiter }} -->
            {{ vaccinationInfos[0].vaccinationDateTime | farmartTime  }}
          </div>
          <div class="text-center">
            {{ vaccinationInfos[0].vaccinationUnitName }}
          </div>
        </div>
        <div class="card" v-if="vaccinationInfos.length == 0" style="padding-top: 20px;" :style="{borderColor:'#e5e5e5'}">
          <div class="flex">
            <img src="../assets/imgs/icon12.png" alt="" />
            <div class="title">新冠疫苗</div>
          </div>
          <div class="text-error">暂无疫苗记录</div>
        </div>
      </div>
<!--      <div class="card opreation">-->
<!--        <div @click="changePhone">切换手机号</div>-->
<!--        <div @click="unbindIdentity">解除绑定</div>-->
<!--      </div>-->

      <div class="bottom">
        <button class="msss" @click="msss">码色申诉</button>
      </div>
    </div>
    <!-- <button @click="exit">离开</button> -->
  </div>
</template>

<script>
import QRCode from "qrcode";
import Vue from "vue";
import { Toast } from "vant";
Vue.use(Toast);
import "vant/lib/index.css";
import VueQr from "vue-qr";
import {Decrypt, parseTime} from "@/utils/AESUtils";
import md5 from "crypto-js/md5";

export default {
  components: {
    VueQr,
  },
  data() {
    return {
      timer:"",
      time: "",
      vaccinationInfos: [],
      nucleicAcidInfos: [],
      loading: false,
      openId: "",
      healthCode: null,
    };
  },
  computed:{
    hours(){
      return  function(i){
        let j = i.replace(/-/g,'/')
        let sTime =Date.parse(new Date(j));
        let eTime = Date.parse(new Date())
        var divNumHour = 1000 * 3600;
        const hour = parseInt((eTime - sTime) / parseInt(divNumHour))
        if (hour <= 48) {
            return '48小时'
        } else if (hour > 48 && hour <= 72) {
            return '72小时'
        } else {
          return ''
        }
      };
    }
  },
  created() {
    Toast.loading({
          message: `<div><span style="font-size:16px;line-height:25px;">加载中...</span></div>`,
          type:"html",
          forbidClick: true,
        });
    /* Toast.loading({
        message: "加载中...",
        forbidClick: true,
        textSize:18,
        size:30,
      }); */
    this.timer= setInterval(()=>{
      this.writeCurrentDate();
    },1000)
    if (sessionStorage.getItem("HealthCode")) {
      let HealthCode = sessionStorage.getItem("HealthCode");
      let data = JSON.parse(decodeURIComponent(HealthCode));
      this.healthCode = {
        codeStr: data.codeStr,
        encodeData: data.encodeData,
        name: data.name,
        personNumber: data.personNumber,
        phone: data.phone,
        value: data.value,
      };
      this.getXgAndHsData();
    } else {
      this.$router.push({
        path: "/",
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    if (to.name == 'healthCode') {
      if (sessionStorage.getItem("HealthCode")) {
        to.meta.keepAlive = true;
      }
    }
    next();
  },
  beforeRouteLeave(to, from, next) {
    let that = this;
    // 路由导航钩子，此时还不能获取组件实例 `this`，所以无法在data中定义变量（利用vm除外）
    // 参考 https://router.vuejs.org/zh-cn/advanced/navigation-guards.html
    // 所以，利用路由元信息中的meta字段设置变量，方便在各个位置获取。这就是为什么在meta中定义isBack
    // 参考 https://router.vuejs.org/zh-cn/advanced/meta.html
    if (to.name == "home") {
      let vnode = that.$vnode;
      let parentVnode = vnode && vnode.parent;
      if (
        parentVnode &&
        parentVnode.componentInstance &&
        parentVnode.componentInstance.cache
      ) {
        var key =
          vnode.key == null
            ? vnode.componentOptions.Ctor.cid +
              (vnode.componentOptions.tag
                ? `::${vnode.componentOptions.tag}`
                : "")
            : vnode.key;
        var cache = parentVnode.componentInstance.cache;
        var keys = parentVnode.componentInstance.keys;

        if (cache[key]) {
          that.$destroy();
          if (keys.length) {
            var index = keys.indexOf(key);
            if (index > -1) {
              keys.splice(index, 1);
            }
          }

          cache[key] = null;
        }
      }
      //判断是从哪个路由过来的，
      //如果是page2过来的，表明当前页面不需要刷新获取新数据，直接用之前缓存的数据即可
    }
    next();
  },
  mounted() {
    /* let that = this;
    window.setInterval(() => {
      setTimeout(that.getXgAndHsData(), 0);
    }, 1000*5); */
  },
  filters: {
    nameFilter(val) {
      return val ? "*" + val.slice(1, val.length) : "**";
    },
    valueFulter(e) {
      return e == "1" ? "无异常" : e == 2 ? "有异常" : "";
    },

    timeFiter(e) {
      if (typeof(e) === 'string') {
        return e.substring(0, 10);
      } else if (typeof(e) === 'number') {
        return parseTime(e).substring(0, 10);
      } else {
        return null;
      }
    },
    farmartTime(e){
      /* var time = new Date(e)
      let year = time.getFullYear();
      let month = time.getMonth()+1;
      let day = time.getDate();
      let hour = time.getHours();
      let min = time.getMinutes();
      let second = time.getSeconds(); */
      
      var change = new Date(e);
      var Y = change.getFullYear() + "-";
      var M = (change.getMonth() + 1 < 10 ? "0" + (change.getMonth() + 1) : change.getMonth() + 1) + "-";
      var D= (change.getDate() < 10 ? "0" + (change.getDate()) : change.getDate()) + " ";
      var h= (change.getHours() < 10 ? "0" + (change.getHours()) : change.getHours()) + ":";
      var m= (change.getMinutes() < 10 ? "0" + (change.getMinutes()) : change.getMinutes()) + ":";
      var s= (change.getSeconds() < 10 ? "0" + (change.getSeconds()) : change.getSeconds());
      var newDate = Y + M + D + h + m + s;     
      return newDate;
    }
  },
  methods: {
    //生成二维码
    code(url) {
      QRCode.colorDark = "#4ca46a";
      QRCode.toDataURL(url)
        .then((url) => {
          this.imrUrl = url;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 根据身份证号获取核酸和新冠疫苗数据
    async getXgAndHsData() {
      /* Toast.loading({
        message: "加载中...",
        forbidClick: true,
      }); */
      const params = {
        personNumber: this.healthCode.personNumber,
        name:this.healthCode.name
      };
      let url = process.env.VUE_APP_BASEURL + "/h5Page/getXgAndHsData?personNumber="+this.healthCode.personNumber+"&name="+this.healthCode.name;
      // let url = "http://192.168.2.205:3020/h5Page/getXgAndHsData?personNumber="+this.healthCode.personNumber+"&name="+this.healthCode.name;
      let timestamp = new Date().getTime();
      let sign = this.getSign(url,timestamp);
      let md = md5(sign)+"";
      const res = await this.$http.get("/h5Page/getXgAndHsData", {
        params: params,
        headers: {
          'UHCC_SIGN': md.toUpperCase(),
          'UHCC_TIMESTAMP': timestamp },
      });
      let response = Decrypt(res.data.data);
      let result = JSON.parse(response);
      console.log(result);
      Toast.clear();
      if (res.data.success == true) {
        this.nucleicAcidInfos = result.nucleicAcidInfos
          ? result.nucleicAcidInfos
          : [];
        this.vaccinationInfos = result.vaccinationInfos
          ? result.vaccinationInfos
          : [];
      }
    },
    getSign(urll,timestamp) {
      const body = undefined;
      const url = new URL(
              urll
      )
      const key = '083b83b0ed1c4d73'

      const signContent = md5(JSON.stringify(body))
      const { search, pathname } = url
      const array = search
              .substring(1)
              .split('&')
              .sort((a, b) => {
                const [k1, v1] = a.split('=')
                const [k2, v2] = b.split('=')
                if (k1.toLowerCase() < k2.toLowerCase()) {
                  return -1
                }
                if (k1.toLowerCase() > k2.toLowerCase()) {
                  return 1
                }
                return 0
              })
      return `&${array.join('&')}&${pathname}&${timestamp}&${key}`;

    },
    // 解除绑定
    async unbindIdentity() {
      const res = await this.$http.post(
        "/h5Page/unbindIdentity?phone=" + this.phone
      );
      if (res.data.success == true) {
        this.$router.push({
          path: "/",
        });
        // Toast("解绑成功");
        Toast.loading({
          message: `<div><span style="font-size:16px;line-height:25px;">解绑成功</span></div>`,
          type:"html",
          forbidClick: true,
        });
      }
    },
    // 切换手机号
    changePhone() {
      this.$router.push({
        path: "/",
      });
    },
    toLogin() {
      window.location.href = 'https://ur.alipay.com/71lwvd'
    },
    nuc() {
      let data = encodeURIComponent(JSON.stringify(this.nucleicAcidInfos));
      this.$router.push({
        path: "/nuc",
        query: { nucleicAcidInfos: data },
      });
    },
    vac() {
      let data = encodeURIComponent(JSON.stringify(this.vaccinationInfos));
      this.$router.push({
        path: "/vac",
        query: { vaccinationInfos: data },
      });
    },

    msss() {
      window.location.href="https://portal.zjzwfw.gov.cn/portal/page/athena-view.html?pageId=10227&_tesseract_=true"
      // window.location.href = 'http://weixin.zjzxts.gov.cn/fhl_web_zj/zhejiang/m/cell/healthCode'
    },
    zlct() {
      // window.location.href = 'https://portal.zjzwfw.gov.cn/hc/p/w/out-epidemic-collect/report-health.html'
    },
    writeCurrentDate: function () {
      let now = new Date();
      let month = now.getMonth() + 1; //得到月份
      let date = now.getDate(); //得到日期
      let hour = now.getHours(); //得到小时
      let minu = now.getMinutes(); //得到分钟
      let time = "";
      time =
        (month < 10 ? "0" + month : month) +
        "月" +
        (date < 10 ? "0" + date : date) +
        "日 " +
        (hour < 10 ? "0" + hour : hour) +
        ":" +
        (minu < 10 ? "0" + minu : minu);
      this.time = time;
    },
    exit(){
      sessionStorage.clear()
      localStorage.clear()
      this.$router.push({
        path: "/",
      });
    }
  },
  beforeDestroy(){
    clearInterval(this.timer);
  },
};
</script>
<style lang="scss" scoped>

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  img {
    width: 40px;
    height: 40px;
  }
}
.health-code {
  background: #f9f9f9;
  // padding-top: 20px;
  // padding-bottom: 20px;
  min-height: 100vh;
  box-sizing: border-box;
  z-index: -9999;
  .whiteBox {
    background: white;
    width: 90%;
    margin: 0 auto;
    box-sizing: border-box;
    padding: 20px 0 20px;
  }
  header {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 100%;
      height: 25rem;
      position: absolute;
      top: 0;
      left: 0;
    }

    span {
      margin: 20px 0;
      font-size: 22px;
      color: #ffffff;
      text-align: center;
      z-index: 1;
    }
  }
  .code {
    width: 90%;
    margin: 0 auto;
    box-sizing: border-box;
    position: relative;
    &-head {
      padding: 15px;
      display: flex;
      justify-content: space-between;
      font-size: 23px;
      padding-right: 20px;
    }
    &-body {
      width: 100%;
      height: 20rem;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      overflow: hidden;
      .banner1 {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }
      .body_title {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        z-index: 1;
        position: absolute;
        top: 15px;
        left: 50%;
        transform: translate(-50%, 0);
        span {
          font-size: 30px;
          margin: 0 10px;
        }
        .left {
          width: 45px;
          height: 15px;
        }
        .right {
          width: 45px;
          height: 15px;
        }
      }
      .vue-qr {
        position: absolute;
        top: 70px;
        left: 50%;
        transform: translate(-50%);
        width: 300px;
        height: 300px;
        z-index: 9;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    &-foot {
      width: 45%;
      font-size: 20px;
      font-weight: bold;
      letter-spacing: 1px;
      text-align: center;
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translate(-50%, -50%);
      background: white;
      padding: 15px;
      border-radius: 40px;
    }
  }
  .trip-code {
    margin: 0 auto 20px;
    width: 90%;
    font-size: 22px;
    padding: 15px;
    border: 1px solid #e5e5e5;
    box-sizing: border-box;
    position: relative;
    .cardTop {
      width: 100%;
      position: absolute;
      top: -1px;
      left: 0px;
    }
    .trip-pic {
      img {
        width: 60px;
        height: 60px;
      }
      position: relative;
      top: -20px;
      width: 60px;
      height: 60px;
      border-radius: 50%;
      margin: 50px auto 0;
    }
  }
  .msss{
    background-color: #64B884;
    width:100%;
    border-radius: 20px;
    border:none;
    color:white;
    height: 60px;

  }
  // .zlct{
  //   background-color: #48A36A;
  //   width:50%;
  //   border-radius: 0px 20px 20px 0px;
  //   border:none;
  //   color:white;
  //   height: 60px;

  // }

  .bottom {
    width: 90%;
    margin: 20px auto;
    display: flex;
    justify-content: space-between;
    font-size: 22px;

  }
  .measure {
    width: 90%;
    margin: 20px auto;
    display: flex;
    justify-content: space-between;
    font-size: 22px;
    .card {
      width: 48%;
      overflow: hidden;
      border: 1px solid #e5e5e5;
      padding-bottom: 20px;
      .timeBox {
            line-height: 20px;
            width: 80px;
            height: 20px;
            border-radius: 5px 0px 5px 0px;
            text-align: center;
            font-size: 20px;
            padding: 5px;
            text-align: center;
      }
      .zhenBox{
        height: 20px;
        border-radius: 5px 0px 5px 0px;
        font-size: 20px;
        padding: 5px;
        line-height: 20px;
      }
      .three{
        width: 80px;
        text-align: center;
        color: #ffffff;
        background: linear-gradient(to right,#ff6f02,#ffba00,#ff6f00);
      }
      .two,.one{
        width: 100%;
        text-align: center;
        color: #ffffff;
        background-color: #64B884;
      }
      .nores{
        /* height: 20px;
        width: 100%; */
        margin-top: 30px;
      }
      .none{
         width: 100%;
        text-align: center;
      }
    }
    .text-error {
      height: 180px;
      line-height: 200px;
      text-align: center;
      color: green;
    }
    .nuclein-result {
      padding: 1.5rem 0;
      text-align: center;
      color: #48a36a;
      font-size: 1.3rem;
      font-weight: 400;
      letter-spacing: 1px;
    }
    
    
    .div{
      // background-color: yellow;
      width: 100%;
      text-align: center;
      font-size: 12px;
      margin:  0  auto;
    }
    .green{
      width: 100%;
      color: green;
      text-align: center;
      font-size: 12px;
      margin:  0  auto;
    }
    .flex {
      justify-content: center;
      div {
        margin-left: 5px;
      }
      img {
        width: 30px;
        height: 30px;
      }
    }
    .vaccines-result {
      padding: 1.5rem 0;
      font-size: 1.3rem;
      font-weight: 400;
      letter-spacing: 1px;
      text-align: center;
      color: #48a36a;
    }
  }
  .opreation {
    width: 90%;
    margin: 10px auto;
    font-size: 22px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    div {
      width: 50%;
      text-align: center;
      padding: 15px;
    }
    div:nth-child(1) {
      border-radius: 50px 0 0 50px;
      background: #64b884;
    }
    div:nth-child(2) {
      border-radius: 0 50px 50px 0;
      background: #48a36a;
    }
  }
}

.card {
  background: #ffffff;
  border-radius: 10px;
}

.text-center {
  text-align: center;
  width: 100%; /*设置宽度*/
  white-space: nowrap; /*设置不折行*/
  text-overflow: ellipsis; /*这就是省略号喽*/
  -o-text-overflow: ellipsis; /*兼容opera*/
  overflow: hidden; /*设置超过的隐藏*/
}
.text-center1 {
  vertical-align: middle;
  text-align: center;
  width: 100%; /*设置宽度*/
  white-space: nowrap; /*设置不折行*/
  -o-text-overflow: ellipsis; /*兼容opera*/
}
.img-right {
  padding-bottom: 5px;
  vertical-align: middle;
  width: 25px;
  height: 25px;
}
.logoBox {
  font-size: 20px;
  color: white;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
